<?php
/**
 * ExaminationType Service.
 * User: Administrator
 * Date: 2020/2/13 0013
 * Time: 下午 2:02
 */
namespace app\api\service\common;

use app\exceptions\OrdinaryException;
use WxPayConfig;
require_once '../extend/wxpay/lib/WxPay.Api.php';

Class Pay {

    /**
     * 订单详情
     * @var string
     */
    private $_data;

    /**
     * @throws OrdinaryException
     */
    public function __construct(array $data)
    {
        if ( !$data['order_number'] || !$data['total']) {
            throw new OrdinaryException('支付信息错误');
        }
        $this->_data = $data;
    }

    /**
     * 小程序支付
     */
    public function xcx()
    {
        // 统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody(config('app.app_name').'-'.($this->_data['body']??'商品'));
        $input->SetOut_trade_no($this->_data['order_number']);
        $input->SetTotal_fee($this->_data['total']*100);
        $input->SetTime_start($this->_data['start_time']??date("YmdHis"));
        $input->SetTime_expire($this->_data['expire_time']??date("YmdHis", time()+(60*30)));
        $input->SetTrade_type('JSAPI');
        $input->SetOpenid(app('request')->userInfo['xcx_openid']);
        $config = new WxPayConfig();
        $order = \WxPayApi::unifiedOrder($config, $input);

        return $this->GetJsApiParameters($order);
    }

    /**
     *
     * 获取jsapi支付的参数
     * @param array $UnifiedOrderResult 统一支付接口返回的数据
     * @throws OrdinaryException
     *
     * @return string
     */
    public function GetJsApiParameters($UnifiedOrderResult)
    {
        if(!array_key_exists("appid", $UnifiedOrderResult)
            || !array_key_exists("prepay_id", $UnifiedOrderResult)
            || $UnifiedOrderResult['prepay_id'] == "")
        {
            throw new OrdinaryException("参数错误");
        }

        $jsapi = new \WxPayJsApiPay();
        $jsapi->SetAppid($UnifiedOrderResult["appid"]);
        $timeStamp = time();
        $jsapi->SetTimeStamp($timeStamp);
        $jsapi->SetNonceStr(Api::getNonceStr());
        $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);

        $config = new WxPayConfig();
        $jsapi->SetPaySign($jsapi->MakeSign($config));
        $parameters = json_encode($jsapi->GetValues());
        return $parameters;
    }

}